package com.hengxinyongli.iam.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hengxinyongli.iam.entity.Department;
import com.hengxinyongli.iam.entity.DepartmentResource;
import com.hengxinyongli.iam.entity.ResItem;
import com.hengxinyongli.iam.entity.User;
import com.hengxinyongli.iam.mapper.DepartmentMapper;
import com.hengxinyongli.iam.mapper.DepartmentResourceMapper;
import com.hengxinyongli.iam.mapper.UserMapper;
import com.hengxinyongli.iam.utils.AssertUtils;
import com.hengxinyongli.iam.web.constant.Res;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author magic
 * @date 2018/9/26/026 16:01
 * @version 1.0
 * Description DepartmentService
 */
@Service
public class DepartmentService {

    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    DepartmentResourceMapper departmentResourceMapper;
    @Autowired
    UserMapper userMapper;

    public PageInfo selectAllDepartments(Integer pageNo, Integer pageSize, String departName, String status) {
        if(Objects.isNull(pageNo)){
            pageNo = Integer.valueOf(1);
        }
        if(Objects.isNull(pageSize)){
            pageSize =  Integer.MAX_VALUE;
        }
        Department department = new Department();
        if (StringUtils.isNotEmpty(departName)){
            department.setName(departName);
        }
        if(StringUtils.isNotEmpty(status)){
            department.setStatus(status);
        }
        PageHelper.startPage(pageNo,pageSize);
        List<Department> departments = departmentMapper.selectByModelSelective(department,false);
        Page<Department> page = ((Page) departments);
        return  page.toPageInfo();
    }

    public Department selectById(String id) {
        Department department =  departmentMapper.selectByPrimaryKey(id);
        AssertUtils.isTrue(Objects.nonNull(department),"部门信息不存在.");
        List<ResItem> resItems = departmentResourceMapper.selectDepartmentRes(id);
        department.setPermits(resItems);
        return department;
    }

    public void departmentsCreate(Department department, Set<String> permits) {
        AssertUtils.isTrue(Objects.nonNull(department),"部门信息不能为空.");
        AssertUtils.isTrue(Objects.nonNull(department.getParentId()),"部门 parentId 不能为空.");
        Department parentDep = departmentMapper.selectByPrimaryKey(department.getParentId());
        AssertUtils.isTrue(Objects.nonNull(parentDep),"上级部门信息不存在.");
        Integer level = parentDep.getLevel() + 1;
        department.setLevel(Short.parseShort(String.valueOf(level)));
        String rootParentId = department.getParentId();
        if(Res.ROOT_ID_LENGTH < department.getParentId().length()){
            rootParentId = rootParentId.substring(0,4);
        }
        String id = departmentMapper.generateId(rootParentId);
        department.setId(id);
        departmentMapper.insertSelective(department);
        /*permits.forEach(pid -> {
            DepartmentResource departmentResource = new DepartmentResource();
            departmentResource.setDeptId(department.getId());
            departmentResource.setResourceId(pid);
            departmentResourceMapper.insertSelective(departmentResource);
        });*/
    }

    public void departmentsUpdate(String id, Department department, Set<String> permits) {
        if(!Res.DEFAULT_ROOT_PARENT_ID.equals(department.getParentId())){
            Department parentDep = departmentMapper.selectByPrimaryKey(department.getParentId());
            AssertUtils.isTrue(Objects.nonNull(parentDep),"上级部门信息不存在.");
        }
        Department currentDep = departmentMapper.selectByPrimaryKey(id);
        AssertUtils.isTrue(Objects.nonNull(currentDep),"部门信息不存在.");
        department.setId(id);
        String currentDepCode = currentDep.getCode() == null ? "":currentDep.getCode();
        departmentMapper.updateByPrimaryKeySelective(department);
        if(StringUtils.isNotBlank(department.getCode()) && !currentDepCode.equals(department.getCode())){
            User cond = new User();
            cond.setDepId(id);
            User update = new User();
            update.setDepCode(department.getCode());
            userMapper.updateByModelSelective(cond,true,update);
        }
        /*DepartmentResource departmentResource = new DepartmentResource();
        departmentResource.setDeptId(id);
        departmentResourceMapper.deleteByModelSelective(departmentResource,true);
        permits.forEach(p->{
            DepartmentResource addRes = new DepartmentResource();
            addRes.setDeptId(id);
            addRes.setResourceId(p);
            departmentResourceMapper.insertSelective(addRes);
        });*/
    }

    public void departmentsDelete(String id) {
        Department currentDep = departmentMapper.selectByPrimaryKey(id);
        AssertUtils.isTrue(Objects.nonNull(currentDep),"部门信息不存在.");
        DepartmentResource departmentResource = new DepartmentResource();
        departmentResource.setDeptId(id);
        List<DepartmentResource> departmentResources = departmentResourceMapper.selectByModelSelective(departmentResource,true);
        //AssertUtils.isTrue(departmentResources.isEmpty(),"当前部门绑定了资源信息,请先解除绑定关系.");
        if(!departmentResources.isEmpty()){
            departmentResourceMapper.deleteByModelSelective(departmentResource,true);
        }
        User user = new User();
        user.setDepId(id);
        List<User> userList = userMapper.selectByModelSelective(user, true);
        AssertUtils.isTrue(userList.isEmpty(),"该部门下还绑定了人员.");
        Department search = new Department();
        search.setParentId(id);
        List<Department> departmentList = departmentMapper.selectByModelSelective(search, true);
        AssertUtils.isTrue(departmentList.isEmpty(),"该部门下还绑定子级部门.");
        departmentMapper.deleteByPrimaryKey(id);
    }

    public List<Department> fetchDepartInfo(String label, Boolean fetchAll) {
        Department department = new Department();
        department.setCode(label);
        List<Department> departments = departmentMapper.selectByModelSelective(department,true);
        if(fetchAll && !departments.isEmpty()){
            LinkedList<Department> linkedList = new LinkedList(departments);
            while(!linkedList.isEmpty()){
                Department parent = linkedList.removeFirst();
                Department searchCondition = new Department();
                searchCondition.setParentId(parent.getId());
                List<Department> departmentChildren = departmentMapper.selectByModelSelective(searchCondition, true);
                departments.addAll(departmentChildren);
            }
        }
       return departments;
    }
}
